﻿using System;
using Runtime.Common.Object;
using Runtime.CoreAttribute;
using Runtime.Common.Interface;
using Runtime.Common.Interface.GameWorld.Core.Interface;
using UnityEngine;

namespace Runtime.DesignPattern
{
    [IgnoreStaticObjectRestore]
    public class SingletonOfObjectThread<T> : MonoBehaviour, IGameSingleton, IInit where T : Component, IGameSingleton
    {
        public static Lazy<T> inst = new(InitFun());

        protected SingletonOfObjectThread()
        {
        }

        public static T Inst => inst.Value;
        public virtual bool IsDestroy { get; } = true;

        public void Reset()
        {
            if (inst.Value)
            {
                Destroy(inst.Value);
                inst = new Lazy<T>(InitFun);
            }
        }

        public IGuidObject Id { get; } = new GuidObject();

        public void Destroy()
        {
            Reset();
        }

        public virtual void Init()
        {
            SingletonRegister.Register(inst.Value);
        }

        private static T InitFun()
        {
            var temp = new GameObject(typeof(T).Name).AddComponent<T>();
            DontDestroyOnLoad(temp);
            return temp;
        }
    }
}